<template>
  <el-table :data="dirs" border style="width: 100%">
    <el-table-column prop="file" label="路径" width="300" />
    <el-table-column prop="link" label="链接" width="600" />
    <el-table-column label="操作">
      <template #default="scope">
        <el-button size="small" @click="handleEdit(scope.row.file, scope.row.link)">修改</el-button>
      </template>
    </el-table-column>
  </el-table>

  <!-- 弹窗 -->
  <el-dialog v-model="dialogFormVisible" title="修改链接" width="600">
    <p>将文件：<span style="color: #79bbff;">{{ filePath }}</span> 的跳转链接</p>
    <p style="margin-bottom: 10px;">从：<span style="color: #79bbff;">{{ oldStr }}</span> 修改为：</p>
    <el-form>
      <el-form-item label="新链接">
        <el-input v-model="newStr" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false" :loading="isloading">取消</el-button>
        <el-button type="primary" @click="updateStr" :loading="isloading">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { onMounted, computed, ref } from 'vue';
import { useStore } from 'vuex';
import axios from 'axios';
import { ElMessage } from 'element-plus'

const store = useStore();

const dirs = computed(() => store.state.dirs);

const newStr = ref('');
const dialogFormVisible = ref(false);

// 文件和旧链接
const filePath = ref('');
const oldStr = ref('');

const isloading = ref(false)

const handleEdit = (file: string, link: string) => {
  dialogFormVisible.value = true;
  filePath.value = file;
  oldStr.value = link;
};

const updateStr = async () => {
  try {
    isloading.value = true;
    newStr.value = newStr.value.trim(); // 去掉两边空格

    const urlPattern = /^(https?:\/\/)/;
    if (!urlPattern.test(newStr.value)) {
      ElMessage({
        showClose: true,
        message: '新链接必须以https或http开头！',
        type: 'error',
      });
      isloading.value = false;
      return;
    }

    if (oldStr.value === newStr.value) {
      ElMessage({
        showClose: true,
        message: '新旧链接相同！',
        type: 'error',
      });
      isloading.value = false;
      return;
    }

    const res = await axios.post('https://api.wotai.org/index.php/api/query/updateStr', {
      auth: 'wotai',
      filepath: filePath.value,
      oldstr: oldStr.value,
      newstr: newStr.value,
    });

    if (res.data.code === 1) {
      store.dispatch('getDirs').then(() => {
        ElMessage({
          showClose: true,
          message: '更新成功',
          type: 'success',
        });
        newStr.value = ''; // 函数结束前将 newStr 设为空
        dialogFormVisible.value = false; // 数据更新后隐藏弹窗
        isloading.value = false;
      });
    }
  } catch (error) {
    console.error('Error updating string:', error);
  }
};

onMounted(() => {
  store.dispatch('getDirs');
});
</script>



<style scoped lang="less">
.el-table {
  height: 100%;
  color: #222;
}
</style>
